#include "PicFrame.h"

namespace simple_renderer{

void PicFrame::Init(){

    if(_frame_type == kI420P || _frame_type == kYV12){

        _pixels = new uint8_t*[3];
        int y_len = _width * _height;
        int u_len = y_len / 4;
        _pixels[0] = _data_ptr;
        _pixels[1] = _data_ptr + y_len;
        _pixels[2] = _data_ptr + y_len + u_len;

        _stride = _width;
        _pitches = new uint16_t[3];
        _pitches[0] = _stride;
        _pitches[1] = _stride / 2;
        _pitches[2] = _stride / 2;

        //_data_length = y_len + u_len * 2;
    }
}

void PicFrame::Deinit(){

    if(_pixels){
        delete [] _pixels;
        _pixels = nullptr;
    }
    if(_pitches){
        delete [] _pitches;
        _pitches = nullptr;
    }
    if(_data_ptr){
        delete [] _data_ptr;
        _data_ptr = nullptr;
    }
}

void PicFrame::CopyData(int w, int h, FrameType type, uint8_t* data, int length){

    if (w != _width || h != _height ||
        type != _frame_type ||
        length != _data_length ||
        _data_ptr == nullptr) {

        _width = w;
        _height = h;
        _frame_type = type;
        _data_length = length;
        if (_data_ptr) {
            delete[] _data_ptr;
        }
        _data_ptr = new uint8_t[_data_length];
        Init();
    }
    memcpy(_data_ptr, data, _data_length);
}

void PicFrame::CopyDataI420(int w, int h, FrameType type, uint8_t* data_y, int len_y, uint8_t* data_u, int len_u, uint8_t* data_v, int len_v){

    if (w != _width || h != _height ||
        type != _frame_type ||
        _data_ptr == nullptr) {

        _width = w;
        _height = h;
        _frame_type = type;
        _data_length = w * h * 3 / 2;
        if (_data_ptr) {
            delete[] _data_ptr;
        }
        _data_ptr = new uint8_t[_data_length];
        Init();
    }
    memcpy(_data_ptr, data_y, len_y);
    memcpy(_data_ptr+len_y, data_u, len_u);
    memcpy(_data_ptr+len_y+len_u, data_v, len_v);
}

PicFrame& PicFrame::operator=(const PicFrame& picFrame){
    if(this == &picFrame){
        return *this;
    }

    if(picFrame._frame_type != kTexture) {
        //copy frame data
        if (this->_data_length == 0) {
            this->_data_length = picFrame._data_length;

        }
    }else {
        //get texture id
        this->_texture_id = picFrame._texture_id;
    }

    return *this;
}

}